//
//  ReBindMobileViewController.m
//  PlayBall
//
//  Created by Huawen Liu on 12-8-29.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "JddBindMobileViewController.h"
#import "JddDataParser.h"
#import "JddUserProfile.h"
#import "JddViewControllerManager.h"

@interface JddBindMobileViewController ()

@end

@implementation JddBindMobileViewController

@synthesize mobileTextField;
@synthesize verifyCodeTextField;
@synthesize getVeriyCodeButton;
@synthesize bindButton;
@synthesize bgScrollView;
@synthesize exBindlabel;
@synthesize exBindMobile;
@synthesize exBindtiplabel;

SHARED_VIEW_CONTROLLER_IMPLEMENT(JddBindMobileViewController);

- (void)GetVerifyCodeOperationResult:(NSData *)result{
    if (result) {
        if([JddDataParser parseGetVerifyCodeRestul:result]){
            [self beginCountSendMsgNextTime];
        }else{
            self.sendMsgBtn.enabled = YES;
        }
        [JddCommonFunction messageBoxWithMessage:[JddError sharedInstance].message];
    }
}

- (IBAction)verifyCodeButtonClicked:(id)sender{
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"^([1][3,4,5,8])([0-9]{9})$"];
    if (![mobileTextField.text length] || ![pred evaluateWithObject:mobileTextField.text]) {
        [JddCommonFunction messageBoxWithMessage:PLEASE_INPUT_MOBILE];
        return;
    }
    
    JddGetVerifyCodeOperation *operation = [[JddGetVerifyCodeOperation alloc] init];
    
    operation.delegate = self;
    operation.mobile = mobileTextField.text;
    [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
    self.sendMsgBtn.enabled = NO;
}

-(void)beginCountSendMsgNextTime
{
    NSDate *sendTime = [NSDate date];
    NSDate *nextSendTimeDate = [sendTime dateByAddingTimeInterval:60];
    [JddUserProfile sharedInstance].nextSendTimeDate = nextSendTimeDate;
}

- (void)BindMobileOperationResult:(NSData *)result{
    if (result) {
        if ([JddDataParser parseBindMobileResult:result]) {
            [JddUserProfile sharedInstance].nextSendTimeDate = nil;
            self.sendMsgBtn.enabled = YES;
//             self.nextSendMsgTimeLbl.text = @"";
            [JddUserProfile sharedInstance].bindMobile = mobileTextField.text;
            [JddUserProfile sharedInstance].IsMobileBind = @"1";
            [JddCommonFunction messageBoxWithMessage:[JddError sharedInstance].message];
            [[JddViewControllerManager sharedInstance] popToBackViewController];
        } else {
            [JddCommonFunction messageBoxWithMessage:[JddError sharedInstance].message];
        }
    }    
}


- (IBAction)bindButtonClicked:(id)sender{
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"^([1][3,4,5,8])([0-9]{9})$"];
    if (![mobileTextField.text length] || ![pred evaluateWithObject:mobileTextField.text]) {
        [JddCommonFunction messageBoxWithMessage:PLEASE_INPUT_MOBILE];
        return;
    }
    //    else if([[UserProfile sharedInstance].bindMobile length]>6&&[[UserProfile sharedInstance].IsMobileBind isEqualToString: @"1"]){
    //        if (![exBindMobile.text isEqualToString:[UserProfile sharedInstance].bindMobile]) {
    //            [JddCommonFunction messageBoxWithMessage:原手机号输入不正确];
    //            return;
    //        }
    //    }
    if (![verifyCodeTextField.text length]) {
        [JddCommonFunction messageBoxWithMessage:PLEASE_INPUT_VERIFY_CODE];
        return;
    }
    
    JddBindMobileOperation *operation = [[JddBindMobileOperation alloc] init];
    
    operation.delegate = self;
//    if ([[UserProfile sharedInstance].bindMobile length]>6&&[[UserProfile sharedInstance].IsMobileBind isEqualToString: @"1"]) {
//        operation.mobile = exBindMobile.text;
//    }else {
        operation.mobile = @"";
//    }
    
    operation.verifyCode = verifyCodeTextField.text;
    
    [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTapGesture:)];
    tapGestureRecognizer.delegate = self;
    [self.bgScrollView addGestureRecognizer:tapGestureRecognizer];
    
    if (textField == self.verifyCodeTextField) {
        [self.bgScrollView setContentOffset:CGPointMake(0, 24) 
                                   animated:YES];
    }
    
    return YES;    
}

- (IBAction)handleSingleTapGesture:(UITapGestureRecognizer*)sender{
    [self.bgScrollView removeGestureRecognizer:sender];
    [exBindMobile resignFirstResponder];
    [mobileTextField resignFirstResponder];
    [verifyCodeTextField resignFirstResponder];
    
    [self.bgScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    if ([touch.view isDescendantOfView:getVeriyCodeButton] ||
        [touch.view isDescendantOfView:bindButton]) {
        return NO;
    }
    
    return YES;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"bindMobile"];
    
    mobileTextField.text = @"";
    exBindMobile.text = @"";
    verifyCodeTextField.text = @"";
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"bindMobile"];
	[MobClick event:@"UserCenter-bindmobile"];

    exBindMobile.text = @"";
    mobileTextField.text= @"";
    verifyCodeTextField.text = @"";
    [exBindMobile resignFirstResponder];
    [mobileTextField resignFirstResponder];
    [verifyCodeTextField resignFirstResponder];
    [self.bgScrollView resignFirstResponder];
    if ([[JddUserProfile sharedInstance].bindMobile length]>5){
        
        if([[JddUserProfile sharedInstance].IsMobileBind intValue]==1) {
            UILabel *customLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 30)];
            customLab.backgroundColor = [UIColor clearColor];
            [customLab setText:@"重新绑定手机号码"];
            customLab.textAlignment = NSTextAlignmentCenter;

            [customLab setTextColor:[UIColor whiteColor]];
            customLab.font = [UIFont systemFontOfSize:19];
            self.navigationItem.titleView = customLab;
            exBindtiplabel.text = @"新手机号码：";
            exBindMobile.hidden = NO;
            exBindlabel.hidden = NO;        
        } else {
            UILabel *customLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 30)];
            customLab.backgroundColor = [UIColor clearColor];
            [customLab setText:PAGE_BIND_MOBILE];
            customLab.textAlignment = NSTextAlignmentCenter;

            [customLab setTextColor:[UIColor whiteColor]];
            customLab.font = [UIFont systemFontOfSize:19];
            self.navigationItem.titleView = customLab;
        
            exBindtiplabel.text = @"手机号码：";
            exBindMobile.hidden = YES;
            exBindlabel.hidden = YES;
        }
    } else {
        UILabel *customLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 30)];
        customLab.backgroundColor = [UIColor clearColor];
        [customLab setText:PAGE_BIND_MOBILE];
        customLab.textAlignment = NSTextAlignmentCenter;

        [customLab setTextColor:[UIColor whiteColor]];
        customLab.font = [UIFont systemFontOfSize:19];
        self.navigationItem.titleView = customLab;
        exBindtiplabel.text = @"手机号码：";
        exBindMobile.hidden = YES;
        exBindlabel.hidden = YES;
    }
}

-(void)confirmMsgDate
{
    NSDate *sendTime = [NSDate date];
    [sendTime dateByAddingTimeInterval:1];
    NSDate *nextSendTimeDate = [JddUserProfile sharedInstance].nextSendTimeDate;
    if (nextSendTimeDate != nil) {
        NSTimeInterval interval = [nextSendTimeDate timeIntervalSinceDate:sendTime];
        if (interval > 1) {
//            NSInteger remainDay = interval / 86400;
//            NSInteger remainHour = (interval - 86400 * remainDay) / 3600;
//            NSInteger remainMinute = (interval - 86400 * remainDay - remainHour * 3600) / 60;
//            NSInteger remainSecond = (interval - 86400 * remainDay - remainHour *3600 - remainMinute * 60);
//          NSString *str = [NSString stringWithFormat:@"%2d分%02d秒后重新获取短信",remainMinute, remainSecond];
//            self.nextSendMsgTimeLbl.text = str;
        }else{
            nextSendTimeDate = nil;
            self.sendMsgBtn.enabled = YES;
//            self.nextSendMsgTimeLbl.text = @"";
        }
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
        UILabel *customLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 30)];
        customLab.backgroundColor = [UIColor clearColor];
        [customLab setText:@"绑定手机"];
        [customLab setTextColor:[UIColor whiteColor]];
        customLab.font = [UIFont systemFontOfSize:19];
        self.navigationItem.titleView = customLab;
        
//        //self.navigationItem.hidesBackButton = YES;

    exBindMobile.hidden = YES;
    exBindlabel.hidden = YES;
    //获取验证码时间
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(confirmMsgDate) userInfo:nil repeats:YES];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
